$(function(){

    var healthbar = $('#health-bar');
    var form = $('#actions-form');

    $('a[rel="damage"]').click(function(){
        console.time('apply damage');
        damage = $('#damage',form);
        if (damage.val()) {
            for(var i = 1; i <= damage.val(); i++) {
		        if ($('span.heart-half', healthbar).length) {
		            $('span.heart-half', healthbar).removeClass('heart-half');
		        } else if ($('span.heart-full', healthbar).length) {
		            $('span.heart-full:last', healthbar).removeClass('heart-full').addClass('heart-half');		            
		        } else {
		            console.log('already dead');
		            break;
		        }
		        
		        if (!$('span.heart-full,span.heart-half', healthbar).length) {
                  console.log('dead');
                  break;                    
                }                
	        }
	        
	        damage.val('');
        }               
        console.timeEnd('apply damage');
        return false;
    });
    
    $('a[rel="heal"]').click(function(){
        heal = $('#heal',form);
        if (heal.val()) {
            for(var i = 1; i <= heal.val(); i++) {
                if ($('span.heart-half', healthbar).length) {
                   $('span.heart-half', healthbar).removeClass('heart-half').addClass('heart-full'); 
                } else if ($('span.heart-full:last', healthbar).next('span').length) {
                    $('span.heart-full:last', healthbar).next('span').addClass('heart-half');
                } else if ($('span.heart-full', healthbar).length == $('span', healthbar).length) {
                    console.log('full');
                    break; 
                } else {
                    console.log('dead');
                    break;
                }                
            }
            heal.val('');
        }
    
        return false;
    });
    
    $('a[rel="add-life"]').click(function(){
        $('<span>').text(($('#health-bar span').length+1)).appendTo('#health-bar');
        return false;               
    });
    
    $('a[rel="remove-life"]').click(function(){
        hearts = $('span', healthbar)
        if (hearts.length > 1) {
            hearts.filter(':last').remove();
        }
        return false;
    });
});